// === 微信画布初始化 ===
const canvas = wx.createCanvas();
const ctx = canvas.getContext('2d');
wx.canvas = canvas;

// === 资源声明 ===
const resources = {
  images: {
    player: 'images/player.png',
    monster: 'images/monster.png',
    bullet: 'images/bullet.png'
  },
  audios: {
    shoot: 'audio/shoot.mp3'
  }
};

// === 游戏对象定义 ===
class Player {
  constructor() {
    this.x = wx.canvas.width / 2;
    this.y = wx.canvas.height / 2;
    this.speed = 5;
    this.shootInterval = 500;
    this.lastShootTime = 0;
    this.radius = 20;
  }

  update() {
    if (touchPos) {
      const dx = touchPos.x - this.x;
      const dy = touchPos.y - this.y;
      const distance = Math.sqrt(dx*dx + dy*dy);

      if (distance > this.speed) {
        this.x += (dx / distance) * this.speed;
        this.y += (dy / distance) * this.speed;
      }
    }
  }

  shoot() {
    const now = Date.now();
    if (now - this.lastShootTime > this.shootInterval) {
      const directions = [
        {dx:1, dy:0}, {dx:-1, dy:0},
        {dx:0, dy:1}, {dx:0, dy:-1}
      ];

      directions.forEach(dir => {
        gameManager.bullets.push(new Bullet(
          this.x,
          this.y,
          dir.dx * 10,
          dir.dy * 10
        ));
      });
      this.lastShootTime = now;
      // 播放音效
      if (audio.shoot) {
        audio.shoot.seek(0);
        audio.shoot.play();
      }
    }
  }
}

// 新增：明确定义Bullet类
class Bullet {
  constructor(x, y, dx, dy) {
    this.x = x;
    this.y = y;
    this.dx = dx;
    this.dy = dy;
    this.radius = 3;
  }

  update() {
    this.x += this.dx;
    this.y += this.dy;
  }
}

// 新增：明确定义Monster类
class Monster {
  constructor() {
    this.x = Math.random() * wx.canvas.width;
    this.y = Math.random() * wx.canvas.height;
    this.speed = 2;
    this.radius = 15;
  }

  update() {
    const dx = gameManager.player.x - this.x;
    const dy = gameManager.player.y - this.y;
    const distance = Math.sqrt(dx*dx + dy*dy);
    
    if (distance > 0) {
      this.x += (dx / distance) * this.speed;
      this.y += (dy / distance) * this.speed;
    }
  }
}

// === 游戏管理器 ===
class GameManager {
  constructor() {
    this.player = new Player();
    this.monsters = [];
    this.bullets = [];
    this.spawnInterval = 3000;
    this.lastSpawnTime = 0;

    for (let i = 0; i < 5; i++) {
      this.monsters.push(new Monster());
    }
  }

  update() {
    this.player.update();
    this.monsters.forEach(m => m.update());
    this.bullets.forEach(b => b.update());
    
    const now = Date.now();
    if (now - this.lastSpawnTime > this.spawnInterval) {
      this.monsters.push(new Monster());
      this.lastSpawnTime = now;
    }
    
    this.checkCollisions();
  }

  checkCollisions() {
    // 移除屏幕外的子弹
    this.bullets = this.bullets.filter(bullet => 
      bullet.x > 0 && 
      bullet.x < wx.canvas.width && 
      bullet.y > 0 && 
      bullet.y < wx.canvas.height
    );

    // 子弹与怪物碰撞检测
    this.bullets.forEach((bullet, bi) => {
      this.monsters.forEach((monster, mi) => {
        const dx = bullet.x - monster.x;
        const dy = bullet.y - monster.y;
        const distance = Math.sqrt(dx*dx + dy*dy);
        
        if (distance < bullet.radius + monster.radius) {
          this.monsters.splice(mi, 1);
          this.bullets.splice(bi, 1);
        }
      });
    });
  }

  render(ctx) {
    ctx.clearRect(0, 0, wx.canvas.width, wx.canvas.height);
    
    // 绘制玩家
    if (resources.images.player && resources.images.player.src) {
      ctx.drawImage(
        resources.images.player,
        this.player.x - this.player.radius,
        this.player.y - this.player.radius,
        this.player.radius * 2,
        this.player.radius * 2
      );
    } else {
      ctx.beginPath();
      ctx.arc(this.player.x, this.player.y, this.player.radius, 0, Math.PI*2);
      ctx.fillStyle = '#3498db';
      ctx.fill();
    }
    
    // 绘制怪物
    this.monsters.forEach(m => {
      if (resources.images.monster && resources.images.monster.width) {
        ctx.drawImage(
          resources.images.monster,
          m.x - m.radius,
          m.y - m.radius,
          m.radius * 2,
          m.radius * 2
        );
      } else {
        ctx.beginPath();
        ctx.arc(m.x, m.y, m.radius, 0, Math.PI*2);
        ctx.fillStyle = '#e74c3c';
        ctx.fill();
      }
    });
    
     // 绘制子弹
     this.bullets.forEach(b => {
      if (resources.images.bullet && resources.images.bullet.width) {
        ctx.drawImage(
          resources.images.bullet,
          b.x - b.radius,
          b.y - b.radius,
          b.radius * 2,
          b.radius * 2
        );
      } else {
        ctx.beginPath();
        ctx.arc(b.x, b.y, b.radius, 0, Math.PI*2);
        ctx.fillStyle = '#2ecc71';
        ctx.fill();
      }
    });
  }
}
// === 输入处理 ===
let touchPos = null;

wx.onTouchStart(e => {
  const touch = e.touches; // 修复：获取第一个触点
  touchPos = {
    x: touch.clientX * wx.canvas.width / window.innerWidth,
    y: touch.clientY * wx.canvas.height / window.innerHeight
  };
  gameManager.player.shoot();
});

wx.onTouchMove(e => {
  const touch = e.touches; // 修复：获取第一个触点
  touchPos = {
    x: touch.clientX * wx.canvas.width / window.innerWidth,
    y: touch.clientY * wx.canvas.height / window.innerHeight
  };
});

wx.onTouchEnd(() => {
  touchPos = null;
});

// === 资源加载 ===
const audio = {};
let gameManager; // 修复：全局游戏管理器

function loadResources() {
   // 加载图片（微信专用API）
   const imagePromises = Object.entries(resources.images).map(([key, path]) => {
    return new Promise((resolve) => {
      const img = wx.createImage();
      img.src = path;
      img.onload = () => {
        resources.images[key] = img;
        resolve();
      };
      img.onerror = () => {
        console.warn(`[微信环境] 图片加载失败: ${path}`);
        resources.images[key] = { width: 0 }; // 标记为无效
        resolve();
      };
    });
  });
  // 加载音频
  const audioPromises = Object.entries(resources.audios).map(([key, path]) => {
    return new Promise((resolve) => {
      const sound = wx.createInnerAudioContext();
      sound.src = path;
      sound.onCanplay(() => {
        audio[key] = sound;
        resolve();
      });
      sound.onError((err) => {
        console.warn(`音频加载失败: ${path}`, err);
        resolve(); // 即使音频加载失败也继续
      });
    });
  });

  Promise.all([...imagePromises, ...audioPromises]).then(() => {
    console.log('所有资源加载完成');
    gameManager = new GameManager(); // 修复：赋值给全局变量
    requestAnimationFrame(update);
  });
}

// === 游戏循环 ===
function update() {
  gameManager.update();
  gameManager.render(ctx);
  requestAnimationFrame(update);
}

// === 启动游戏 ===
loadResources();
